package com.sike.netty.jinjie.eventloop.executor;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class EventExecutorGroupTestServer {
    public static void main(String[] args) {
        // 新建 EventExecutorGroup 实例对象
        EventExecutorGroup executorGroup = new DefaultEventExecutorGroup(4);

        // 创建服务端启动引导器
        ServerBootstrap bootstrap = new ServerBootstrap();
        // 配置线程组
        bootstrap.group(new NioEventLoopGroup());
        // 指定服务单的 IO 模型
        bootstrap.channel(NioServerSocketChannel.class);

        // 定义处理器 Handler
        bootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                // 解码
                ch.pipeline().addLast(new StringDecoder());

                ch.pipeline().addLast(executorGroup,new ChannelInboundHandlerAdapter(){
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        log.info("接收客户端信息：" + msg);
                        log.info("开始执行普通任务");
                        ctx.executor().execute(() -> {
                            try {
                                log.info("开始执行任务...");
                                TimeUnit.SECONDS.sleep(5);
                                log.info("任务执行完成...");
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        });
                    }
                });
            }
        });
        // 绑定 8081 端口
        bootstrap.bind(8081);
    }
}
